package br.com.carser.dao;

import java.util.List;

import javax.inject.Named;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.carser.dao.infra.BaseDAO;
import br.com.carser.model.User;

/**
 * Class to user manager persistence.
 * 
 * @author Eduardo T. Serete
 */
@Named
public class UserDAO extends BaseDAO<User> {
	
	public static final String QUERY_GET_USERNAME_PASSWORD = "User.getByUserNamePassword";
	
	public static final String QUERY_GET_EMAIL_PASSWORD = "User.getByUserNamePassword";
	
	public static final String QUERY_GET_NAME_USERNAME = "User.getByNameUsername";

	/**
	 * Method to get one user By name or password.
	 * 
	 * @param String
	 *            : user name
	 * @param String
	 *            : password.
	 * 
	 * @return User: if encounter a user in database
	 */
	public User getByUserNamePassword(String username, String password) {
		Query query = getEntityManager().createNamedQuery(QUERY_GET_USERNAME_PASSWORD);
		query.setParameter("username", username);
		query.setParameter("password", password);
		try {
			return (User) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
		
	}

	/**
	 * Get user by email.
	 * 
	 * @param String
	 *            : email.
	 * 
	 * @return User: user.
	 */
	public User getByEmail(String email) {
		Query query = getEntityManager().createNamedQuery(QUERY_GET_EMAIL_PASSWORD);
		query.setParameter("email", email);
		return (User) query.getSingleResult();
	}

	/**
	 * Filter do get users by name and user name.
	 * 
	 * @param String
	 *            : name
	 * @param String
	 *            : user name
	 * @return List<User>: list of users.
	 */
	@SuppressWarnings("unchecked")
	public List<User> getByNameUsername(String name, String username) {
		Criteria criteria = this.getHibernateCriteria();
		if(name != null && !name.isEmpty()) {
			criteria.add(Restrictions.like("name", name, MatchMode.ANYWHERE));
		}
		if(username != null && !username.isEmpty()) {
			criteria.add(Restrictions.like("username", username, MatchMode.ANYWHERE));
		}
		criteria.addOrder(Order.asc("name"));
		return criteria.list();
	}
	
}
